<template>
  <DetailFormProvider>
    <div class="main">
      <div class="form_content">
        <NScrollbar>
          <div class="content">
            <NSpace>
              <NForm
                ref="formRef"
                :model="formValue"
                :rules="rules"
                label-placement="left"
                :label-width="115"
                label-align="right"
                require-mark-placement="left"
                :disabled='route.query.disabled||false'
              >
                <NSpace>
                  <NFormItem
                    label="藏品名称:"
                    path="collectionName"
                  >
                    <NInput
                      v-model:value="formValue.collectionName"
                      placeholder="输入藏品名称"
                      style="width: 250px"
                    />
                  </NFormItem>
                  <NFormItem label="征集时间:"  path="collectionTime">
                    <NDatePicker
                      input-readonly
                      placeholder="请选择征集时间"
                      type="date"
                      value-format="yyyy-MM-dd"
                      v-model:formatted-value="formValue.collectionTime"
                      style="width: 250px"
                      clearable
                    />
              </NFormItem>
                  <NFormItem
                    label="接收人:"
                    path="receiver"
                  >
                    
                    <NInput
                      v-model:value="formValue.receiver"
                      placeholder="输入接收人"
                      style="width: 250px"
                    />
                  </NFormItem>
                </NSpace>
                <NSpace>
                  <NFormItem
                    label="语种:"
                    path="language"
                  >
                    <NInput
                      v-model:value="formValue.language"
                      placeholder="输入语种"
                      style="width: 250px"
                    />
                  </NFormItem>
                  <NFormItem
                    label="出版社:"
                    path="publisher"
                  >
                    <NInput
                      v-model:value="formValue.publisher"
                      placeholder="输入出版社"
                      style="width: 250px"
                    />
                  </NFormItem>
                  <NFormItem
                    label="所在位置名称:"
                    path="location"
                  >
                    <NInput
                      v-model:value="formValue.location"
                      placeholder="输入所在位置名称"
                      style="width: 250px"
                    />
                  </NFormItem>
                </NSpace>
                <NSpace>
                  <NFormItem
                    label="馆藏码:"
                    path="assetCode"
                  >
                    <NInput
                      v-model:value="formValue.assetCode"
                      placeholder="输入馆藏码"
                      style="width: 250px"
                    />
                  </NFormItem>
                  <NFormItem
                    label="入藏总登记号:"
                    path="collectionRegNumber"
                  >
                    <NInput
                      v-model:value="formValue.collectionRegNumber"
                      placeholder="输入入藏总登记号"
                      style="width: 250px"
                    />
                  </NFormItem>
                  <NFormItem label="鉴定时间:" path="appraisalTime">
                    <NDatePicker
                      input-readonly
                      placeholder="请选择鉴定时间"
                      type="date"
                      value-format="yyyy-MM-dd"
                      v-model:formatted-value="formValue.appraisalTime"
                      style="width: 250px"
                      clearable
                    />
              </NFormItem>
                </NSpace>
                <NSpace>
                  <!-- <NFormItem
                    path="certificateTypeCode"
                    label="证书类型:"
                  >
                    <NSelect
                      :options="listOptionCer"
                      v-model:value="formValue.certificateTypeCode"
                      placeholder="请选择证书类型"
                      @update:value="valueChange1"
                      clearable
                      style="width: 250px"
                    />
                  </NFormItem> -->
                  <NFormItem label="编目时间:" path="catalogingTime">
                    <NDatePicker
                      input-readonly
                      placeholder="请选择编目时间"
                      type="date"
                      value-format="yyyy-MM-dd"
                      v-model:formatted-value="formValue.catalogingTime"
                      style="width: 250px"
                      clearable
                    />
              </NFormItem>
                  <NFormItem label="修复时间:" path="restorationTime">
                    <NDatePicker
                      input-readonly
                      placeholder="请选择修复时间"
                      type="date"
                      value-format="yyyy-MM-dd"
                      v-model:formatted-value="formValue.restorationTime"
                      style="width: 250px"
                      clearable
                    />
              </NFormItem>
                  <NFormItem label="展陈时间:" path="exhibitionTime">
                    <NDatePicker
                      input-readonly
                      placeholder="请选择展陈时间"
                      type="date"
                      value-format="yyyy-MM-dd"
                      v-model:formatted-value="formValue.exhibitionTime"
                      style="width: 250px"
                      clearable
                    />
              </NFormItem>
                </NSpace>

                <NSpace>
                  <NFormItem label="保护/研究时间:" path="studyTime">
                    <NDatePicker
                      input-readonly
                      placeholder="请选择保护/研究时间"
                      type="date"
                      value-format="yyyy-MM-dd"
                      v-model:formatted-value="formValue.studyTime"
                      style="width: 250px"
                      clearable
                    />
              </NFormItem>
              <NFormItem label="接收时间:" path="receivedTime">
                    <NDatePicker
                      input-readonly
                      placeholder="请选择接收时间"
                      type="date"
                      value-format="yyyy-MM-dd"
                      v-model:formatted-value="formValue.receivedTime"
                      style="width: 250px"
                      clearable
                    />
              </NFormItem>
                  <NFormItem label="入藏时间:" path="collectedTime">
                    <NDatePicker
                      input-readonly
                      placeholder="请选择入藏时间"
                      type="date"
                      value-format="yyyy-MM-dd"
                      v-model:formatted-value="formValue.collectedTime"
                      style="width: 250px"
                      clearable
                    />
              </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem label="三维信息:" path="threeDimensionalInfo">
                  <NInput
                      v-model:value="formValue.threeDimensionalInfo"
                      placeholder="请输入三维信息"
                      type="textarea"
                      :rows="2"
                      style="width: 250px"
                    />
              </NFormItem>
              <NFormItem
                    label="来源:"
                    path="methodCode"
                  >
                  <NSelect
                    :options="collectFactionList"
                    v-model:value="formValue.methodCode"
                    placeholder="请选择来源"
                    clearablex
                    filterable
                     style="width: 250px"
                  />
                  </NFormItem>
                  <NFormItem label="重要藏品:" path="important">
                  <NSelect
                    :options="[
                      { value: '是', label: '是' },
                      { value: '否', label: '否' }
                    ]"
                    v-model:value="formValue.important"
                    placeholder="请选择重要藏品"
                    style="width: 200px; margin-right: 20px"
                  />
               </NFormItem>
                </NSpace>
                <NSpace>
                  <n-form-item
                  label="选择数据去向"
                  path="dataDestination"
                  v-if="route.params.id=='0'||route.params.id"
                >
                  <n-checkbox-group v-model:value="formValue.dataDestination" style="width: 200px; margin-right: 20px">
                    <n-space item-style="display: flex;">
                      <n-checkbox
                        value="B3大屏"
                        label="B3大屏"
                      />
                      <n-checkbox
                        value="互动查询"
                        label="互动查询"
                      />
                    </n-space>
                  </n-checkbox-group>
                   </n-form-item>
                </NSpace>
                <NSpace>
                  <NFormItem
                    label="藏品简介:"
                    path="description"
                  >
                    <NInput
                      v-model:value="formValue.description"
                      placeholder="输入藏品简介"
                      style="width: 1000px"
                      type="textarea"
                    />
                  </NFormItem>
                </NSpace>
                <NSpace>
                  <!-- <NFormItem
                    label="版本图谱:"
                    path="spectrumIds"
                  >
                    <FUploader
                      :file-list="spectrumIdsList"
                      @update:file-list="handleUploadSpectrumIdsList"
                      style="width: 250px"
                    />
                  </NFormItem> -->
                  <NFormItem
                    label="版本展示图片:"
                    path="displayImageIds"
                  >
                    <FUploader
                      :file-list="displayImageIdsList"
                      @update:fileList="handleUploadDisplayImageIdsList"
                      style="width: 250px"
                    />
                  </NFormItem>
                  <NFormItem
                    label="图片列表:"
                    path="imageIds"
                  >
                    <FUploader
                      :file-list="imageIdsList"
                      @update:fileList="handleUploadImageIdsList"
                      style="width: 250px"
                    />
                  </NFormItem>

                </NSpace>
              </NForm>
            </NSpace>
          </div>
        </NScrollbar>
      </div>
    </div>
    <FixedAction>
      <NSpace justify="center">
        <NButton
          style="width: 78px"
          ghost
          @click="goBack"
        >
          取消
        </NButton>
        <NButton
          type="primary"
          style="width: 78px"
          @click="confirm"
          :disabled="loading"
          :loading="loading"
          v-if="!route.query.disabled"
        >
          保存
        </NButton>
      </NSpace>
    </FixedAction>
  </DetailFormProvider>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted, type VNode, reactive, h,watch} from 'vue'
  import {
    NSpace,
    NForm,
    NInput,
    NDatePicker,
    NFormItem,
    NButton,
    NScrollbar,
    NSelect,
    useMessage,
    NTooltip,
    NCheckbox,
    NCheckboxGroup,
    type SelectOption
  } from 'naive-ui'
  import type { FormInst } from 'naive-ui'
  import router from '@/router'
  import { useRoute } from 'vue-router'
  import { useTagStore } from '@/stores/layout'
  import FixedAction from '@/components/FixedAction.vue'
  import { sendRequest } from '@/utils/api'
  // import VUpload from '@/views/OA/Common/Upload.vue'
  import type { HttpResponse } from '@/utils/http'
  import { keysOf } from '@/utils/object'
  import FUploader from '@/views/Collection/Collect/Batch/components/FUploader.vue'
  const route = useRoute()
  const renderOption = ({ node, option }: { node: VNode; option: SelectOption }) =>
    h(NTooltip, null, {
      trigger: () => node,
      default: () => option.label
    })

  const collectFactionList = ref()
  const tags = useTagStore().tags
  const message = useMessage()
  const loading = ref(false)
  const formRef = ref<FormInst | null>(null)
  const listOption = ref([])
  const listOptionCer = ref([])
  const formValue = reactive({
    collectionName: '',
    collectionTime:null,
    receiver:'',
    methodCode: null,
    important:'否',
    dataDestination:null,
    language: '',
    description:'',
    studyTime: null,
    restorationTime:null,
    exhibitionTime:null,
    collectionRegNumber:'',
    assetCode: '',
    catalogingTime: null,
    appraisalTime: null,
    location: '',
    publisher:'',
    spectrumIds:'',
    displayImageIds:'',
    imageIds:'',
    receivedTime: null,
    collectedTime: null,
    threeDimensionalInfo: ''
  })
  
  const fileList: any = ref([])
  const rules = {
    collectionName: {
      required: true,
      trigger: ['input', 'blur', 'change'],
      validator: (_: any, value: any) => {
        if (value?.length == 0) return new Error('请输入藏品名称')
        if (value?.length > 1000) return new Error('藏品名称字数不得超过1000')
        return true
      }
    },
    receiver: {
      required: true,
      trigger: ['input', 'blur', 'change'],
      validator: (_: any, value: any) => {
        if (value?.length == 0) return new Error('请输入接收人')
        if (value?.length > 1000) return new Error('接收人字数不得超过1000')
        return true
      }
    },
    assetCode: {
      required: true,
      trigger: ['input', 'blur', 'change'],
      validator: (_: any, value: any) => {
        if (value?.length == 0) return new Error('请输入馆藏码')
        if (value?.length > 1000) return new Error('馆藏码字数不得超过1000')
        return true
      }
    },
    location: {
      required: true,
      trigger: ['change', 'blur', 'input'],
      validator: (_: any, value: any) => {
        if (value?.length == 0) return new Error('请输入所在位置名称')
        if (value?.length > 1000) return new Error('所在位置名称字数不得超过1000')
        return true
      }
    },
    // 来源
    methodCode: {
      required: true,
      trigger: ['input', 'blur'],
      type: 'number',
      validator: (_: any, value: any) => {
        if (value == null) return new Error('请输入来源')
        if (value > 1000) return new Error('来源字数不得超过1000')
        return true
      }
      // validator: (_: any, value: any) => {
      //   if (value?.length == 0) return new Error('请输入捐赠数量')
      //   if (!/^[0,9]*/.test(value) || value < 1) return new Error('捐赠数量必须大于0的整数')
      //   if (value?.length > 7) return new Error('捐赠数量字数不得超过10000000')
      //   return true
      // }
    },
    // 藏品简介
    description: {
      required: true,
      trigger: ['input', 'blur', 'change'],
      validator: (_: any, value: any) => {
        if (value?.length == 0) return new Error('请输入藏品简介')
        if (value?.length > 1000) return new Error('藏品简介字数不得超过1000')
        return true
      }
    },
    displayImageIds: {
      required: true,
      trigger: ['change', 'blur', 'input'],
      validator: (_: any, value: any) => {
        console.log(value)
        if (value?.length == 0) return new Error('请选择版本展示图片')
        return true
      }
    },
    imageIds: {
      required: true,
      trigger: ['change', 'blur', 'input'],
      validator: (_: any, value: any) => {
        console.log(value)
        if (value?.length == 0) return new Error('请选择图片列表')
        return true
      }
    }
  }
  const spectrumIdsList = ref<any>([])
  // 附件
  const handleUploadSpectrumIdsList = (v: any) => {
    formValue.spectrumIds = v.map((e: any) => e.file?.remoteId).join(',')
    spectrumIdsList.value = v
  }
  const displayImageIdsList = ref<any>([])
  // 附件
  const handleUploadDisplayImageIdsList = (v: any) => {
    formValue.displayImageIds = v.map((e: any) => e.file?.remoteId).join(',')
    displayImageIdsList.value = v
  }
  const imageIdsList = ref<any>([])
  // 附件
  const handleUploadImageIdsList = (v: any) => {
    formValue.imageIds = v.map((e: any) => e.file?.remoteId).join(',')
    imageIdsList.value = v
  }
  // 返回
  const goBack = () => {
    const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  
    tags.splice(index, 1)
    if (tags.length == 0) {
      router.push({ path: '/OA/Workbench/UserDesktop' })
    } else history.back()
  }
  const listNameOption = ref<any>([])
  //藏家姓名下拉
  const getNameFunction = async () => {
    const [error, res] = await sendRequest<HttpResponse>({
      module: 'clue',
      api: 'controllerOptions'
    })
    if (error) return message.error(error.message)
    listNameOption.value = res.data
  }
  //所属批次下拉
  const getFunction = async (v?: any, m?: any) => {
    const [error, res] = await sendRequest<HttpResponse>({
      module: 'baseDonateCertificate',
      api: 'listBatchOptionsByCollectorIdList',
      override: {
        params: {
          collectorId: m,
          batchName: v
          // id: route.params.id as never
        }
      }
    })
    if (error) return message.error(error.message)
    listOption.value = res.data
  }
  const getFunctionCer = async () => {
    listOptionCer.value = []
    const [error, res] = await sendRequest<HttpResponse>({
      module: 'baseDonateCertificate',
      api: 'listByParentCode',
      override: {
        params: {
          dicCode: 'A61'
        }
      }
    })
    if (error) return message.error(error.message)
    res.data.forEach((i: any) => {
      // @ts-ignore
      listOptionCer.value.push({ label: i.dicName, value: i.dicCode })
    })
  }
 
  //修改
  const confirm = () => {
    formRef.value?.validate(async (err: any) => {
      if (err) return
      loading.value = true
      const [error, res] = await sendRequest<HttpResponse>({
        module: 'dataDistribution',
        api:route.params.id==0||route.params.id?'update':'save' ,
        override: {
          data: {
            ...formValue,
            id:route.params.id,
            dataDestination:route.params.id==0||route.params.id?formValue.dataDestination?.join(','):route.query?.dataDestination,
            spectrumIds:formValue.spectrumIds||'',
            displayImageIds:formValue.displayImageIds||'',
            imageIds:formValue.imageIds||'',
            method:collectFactionList.value?.filter((e: any) => formValue.methodCode==e.value)?.[0]?.label,
          }
        }
      })
      loading.value = false
      if (error) return message.error(error.message)
      message.success(res.msg)
      goBack()
    })
  }
  const codeFn = async (code: any, refValue: any) => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'listByParentCode',
    override: {
      params: {
        dicCode: code
      }
    }
  })
  if (error) return message.error(error.message)
  refValue.value = res?.data?.map((it: any) => {
    return { value: it.dicCode, label: it.dicName }
  })
}
const queryFileList = async (filesIds: string,temp:any) => {
  try {
    const [error, res] = await sendRequest<
      HttpResponse<
        {
          name: string
          path: string
          id: string
          type: string
        }[]
      >
    >({
      module: 'upload',
      api: 'list',
      override: {
        params: {
          ids: filesIds
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    temp.value = res.data.map((e) => ({
      id: e.id,
      path: e.path,
      name: e.name,
      url: e.path,
      status: 'finished',
      file: {
        remoteId: e.id
      }
    })) as unknown as UploadFileInfo[]
  } catch (error) {
    console.error(error)
  }
}
// 获取详情
const spinShow = ref(false)
const getDispatchInfo = async () => {
  spinShow.value = true
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'dataDistribution',
    api: 'info',
    uri: {
      id: route.params.id as never
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  // fileList.value = res.data.fileList.map((e: any) => ({
  //   id: e.id,
  //   name: e.name,
  //   url: e.path,
  //   status: 'finished',
  //   file: {
  //     remoteId: e.id
  //   }
  // }))
  
  keysOf(res.data).forEach((e) => {
    // @ts-ignore
    formValue[e] = res.data[e]
  })
  if (res.data?.imageIds) queryFileList(res.data.imageIds,imageIdsList)
  if (res.data?.displayImageIds) queryFileList(res.data.displayImageIds,displayImageIdsList)
  if (res.data?.spectrumIds) queryFileList(res.data.spectrumIds,spectrumIdsList)
  // debugger
  formValue.dataDestination = res.data?.dataDestination.split(',')
  formValue.appraisalTime = formValue.appraisalTime?.split(' ')?.[0]
  formValue.catalogingTime = formValue.catalogingTime?.split(' ')?.[0]
  formValue.exhibitionTime = formValue.exhibitionTime?.split(' ')?.[0]
  formValue.restorationTime = formValue.restorationTime?.split(' ')?.[0]
  formValue.studyTime = formValue.studyTime?.split(' ')?.[0]
  formValue.collectionTime = formValue.collectionTime?.split(' ')?.[0]
  formValue.receivedTime = formValue.receivedTime?.split(' ')?.[0]
  formValue.collectedTime = formValue.collectedTime?.split(' ')?.[0]
  spinShow.value = false
}
watch(
  () => route,
  () => {
    if (route.name == 'dataTranslateDetail'||route.name == 'dataTranslateEdit') {
      getDispatchInfo()
    }
  },
  { deep: true, immediate: true }
)
  onMounted(() => {
    getFunction()
    getNameFunction()
    getFunctionCer()
    codeFn('A30', collectFactionList) //来源A30
    if(route.params.id=='0'||route.params.id)
    getDispatchInfo()
  })
  </script>
  
  <style scoped lang="scss">
  @mixin CommonFont {
    font-size: 16rem;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.85);
  }
  
  .commonWidth {
    width: 360rem;
  }
  
  .main {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    overflow: hidden;
  
    .topTitle {
      width: 100%;
      height: 64rem;
      border-bottom: 1px solid #fff;
      padding: 20rem;
      margin-bottom: 20rem;
      @include CommonFont;
    }
  
    .form_content {
      width: 100%;
      height: 100%;
      padding: 20rem 20rem 0;
  
      .content {
        display: flex;
        align-items: center;
        flex-direction: column;
        width: 100%;
        height: 100%;
        padding: 18rem 33rem 120rem;
        overflow-y: scroll;
        background-color: #ebeceb;
  
        .scope {
          width: 360rem;
          height: 130rem;
          background: #e1e1e1;
          margin-bottom: 25rem;
        }
      }
    }
  }
  
  .content::-webkit-scrollbar {
    display: none;
  }
  
  :deep(.n-spin-container) {
    width: 100%;
    height: 100%;
  }
  
  :deep(.n-scrollbar-container) {
    width: 100%;
    height: 100%;
  }
  
  :deep(.n-scrollbar-content) {
    width: 100%;
    height: 100%;
  }
  
  :deep(.n-spin-content) {
    width: 100%;
    height: 100%;
  }
  </style>
  